package jmu.service.impl;

import jmu.dao.MessageDAO;
import jmu.dao.RevertDAO;
import jmu.db.ConnectionManager;
import jmu.service.MessageService;
import jmu.vo.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    MessageDAO messageDAO;

    @Autowired
    RevertDAO revertDAO;

    @Override
    public List<Message> list() {
        try {
            // 调用 DAO 层方法获取所有留言
            return messageDAO.findAllMessages();
        } catch (Exception e) {
            e.printStackTrace();
            return List.of();   // 返回空列表
        }
    }

    @Override
    public boolean add(Message message) {
        boolean insertMessages;
        try {
            insertMessages = messageDAO.insertMessages(message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return insertMessages;
    }

    @Override
    public boolean update(Message message) {
        boolean updateMessages;
        try {
            updateMessages = messageDAO.updateMessages(message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return updateMessages;
    }

    @Override
    public boolean delete(int id) {
        Connection con = null;
        try {
            con = ConnectionManager.getConnection();
            con.setAutoCommit(false);

            boolean deleteMessages = messageDAO.deleteMessages(id);

            con.commit();
            return deleteMessages;
        } catch (Exception e) {
            if (con != null) {
                try {
                    con.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            throw new RuntimeException(e);
        } finally {
            ConnectionManager.closeConnection(con);
        }
    }

    @Override
    public List<Message> search(String keyword) {
        try {
            return messageDAO.searchMessages(keyword);
        } catch (Exception e) {
            e.printStackTrace();
            return List.of();
        }
    }

    @Override
    public Message findMessageById(int id) {
        try {
            return messageDAO.findMessageById(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
